<template>
  <div>
    <el-form :model="pwdForm" :rules="rules" ref="ruleForm" label-width="100px" >
    <el-form-item label="原密码" prop="old_pwd">
      <el-input v-model="pwdForm.old_pwd"></el-input>
    </el-form-item>
    <el-form-item label="新密码"  prop="new_pwd">
      <el-input v-model="pwdForm.new_pwd"></el-input>
    </el-form-item>
    <el-form-item label="确认新密码"  prop="re_pwd">
      <el-input v-model="pwdForm.re_pwd"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updatePwd">修改</el-button>
      <el-button @click="resetFields">重置</el-button>
    </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data(){
      // 检测新旧密码是否相同
      const samePwd = (rule, value, callback) => {
        if (value === this.pwdForm.old_pwd) {
          return callback(new Error('新旧密码不能相同！'))
        }
        callback()
      }
      // 检测两次新密码是否一致
      const rePwd = (rule, value, callback) => {
        if (value !== this.pwdForm.new_pwd) {
          return callback(new Error('两次新密码不一致！'))
        }
        callback()
      }
    return{
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: '',
      },
      rules:{
          // 表单的验证规则对象
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' },
          { validator: samePwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    //重置表单
    resetFields(){
      this.$refs.ruleForm.resetFields()
    },
    //提交修改
    updatePwd(){
      // console.log(1);
      this.$refs.ruleForm.validate(async (valid)=>{
        if(!valid)return
        const {data:res} = await this.$axios.patch("/my/updatepwd",this.pwdForm)
        // console.log(res);
        if(res.code !=0 ) return this.$message.error('更新密码失败')
        this.$message.success('更新密码成功')
        this.resetFields()
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .el-form {
    width: 500px;
  }
</style>